<?php
/*
 * @Author: your name
 * @Date: 2022-02-08 21:41:54
 * @LastEditTime: 2022-02-10 09:41:28
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /nlog/app/Http/Controllers/mysql_async/MysqlAsync.php
 */

namespace App\Http\Controllers\mysql_async;

use Swoole\Coroutine\MySQL;
// use Swoole\Coroutine\PostgreSQL;

class MysqlAsyncFunction
{
  
    protected $mysqlAsync;

    public function __construct()
    {
        $this->mysqlAsync = new MySQL();
        $config = config('database.connections.mysql');  //获取laravel数据库配置
        $this->mysqlAsync->connect([
            'host'     => $config['host'],
            'port'     => $config['port'],
            'user'     => $config['username'],
            'password' => $config['password'],
            'database' => $config['database'],
        ]);
      
    }

    public function insert($tableName, $data)
    {
        $insertArray = [
            'keyStr' => '',
            'valStr' => ''
        ];
        foreach ($data as $key => $val) {
            $insertArray['keyStr'] .= '`' . $key . '`,';
            $insertArray['valStr'] .= '"' . $val . '",';
        }

        $sql = 'INSERT INTO `' . $tableName . '` (' . substr($insertArray['keyStr'], 0, -1) . ') VALUES (' . substr($insertArray['valStr'], 0, -1) . ') ';

        return  $this->execute($sql);
    }

    /**
     * @description: 执行MySQL语句
     * @param  string  $sql  MySQL的语句
     * @return mixed
     */
    public function execute($sql = 'SELECT sleep(5)')
    {
        $res =   $this->mysqlAsync->query($sql);
        if ($res) {
            return $res;
        } else {
            return   new \RuntimeException($this->mysqlAsync->connect_error, $this->mysqlAsync->errno) ;
        }

        // $this->mysqlAsync->query($sql,function($db, $r){
        //     if (!$r) {
        //         echo   new \RuntimeException($db->connect_error, $db->errno) ;
        //         // echo "新增数据失败, 错误信息: " . $db->error . ", 错误码: " . $db->errno . "\n";
        //     } elseif ($r == true) {
        //         // return $r;
        //     }
        //     // $db->close();
        // });

    }

    
}

class Myface
{
    public static function __callStatic($methodname, $arguments)
    {
        $classname = static::getFacadeClass();
        $obj = new $classname();
        return call_user_func_array([$obj, $methodname], $arguments);
    }
}

class MysqlAsync extends Myface
{
    public  static function  getFacadeClass()
    {
        return 'App\Http\Controllers\mysql_async\MysqlAsyncFunction';
    }
}
